<template>
  <div class="user">
    <!-- 搜索/重置 -->
    <el-card>
      <el-form inline class="user-form">
        <el-form-item label="用户名:">
          <el-input v-model="keyword" placeholder="请输入搜索的用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="!keyword" @click="search">搜索</el-button>
          <el-button type="default" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 表格 -->
    <el-card style="margin: 10px 0;" >
      <el-button type="primary" @click="addUser">添加用户</el-button>
      <el-button type="danger" :disabled="!selectIdArr.length" @click="delectSelectUser">批量删除</el-button>
      <el-table border style="margin: 10px 0;" :data="userList" @selection-change="selectChange">
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column label="#" type="index"  align="center"></el-table-column>
        <el-table-column label="ID"  align="center" prop="id"></el-table-column>
        <el-table-column label="用户名字"  align="center" prop="username"></el-table-column>
        <el-table-column label="用户名称"  align="center" prop="name"></el-table-column>
        <el-table-column label="用户角色"  align="center" prop="roleName" show-overflow-tooltip></el-table-column>
        <el-table-column label="创建时间"  align="center" prop="createTime" show-overflow-tooltip></el-table-column>
        <el-table-column label="更新时间"  align="center" prop="updateTime" show-overflow-tooltip></el-table-column>
        <el-table-column width="300" label="操作"  align="center">
          <template #default="{row}">
            <el-button type="primary" size="small" icon="User" @click="setRole(row)">分配角色</el-button>
            <el-button type="warning" size="small" icon="Edit" @click="updateUser(row)">编辑</el-button>
            <el-popconfirm @confirm="deleteUser(row.id)" width="200" :title="`确认删除${row.username}吗`">
              <template #reference>
                <el-button type="danger" size="small" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5,7,9,11]"
        background
        layout=" prev, pager, next, jumper,->, total, sizes,"
        :total="total"
        @size-change="sizeChange"
        @current-change="getHasUser"
      />
    </el-card>
    <!-- 抽屉 添加修改用户 -->
    <el-drawer v-model="drawer" direction="rtl">
      <template #header>
        <h4>{{ userParams.id?'更新用户':'添加用户' }}</h4>
      </template>
      <template #default>
        <el-form ref="formRef" :model="userParams" :rules="rules">
          <el-form-item label="用户名字" prop="username">
            <el-input  v-model="userParams.username" placeholder="请输入用户名字"></el-input>
          </el-form-item>
          <el-form-item label="用户名称" prop="name">
            <el-input  v-model="userParams.name" placeholder="请输入用户名称"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
            <el-input  v-model="userParams.password" placeholder="请输入用户密码"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 抽屉 分配角色  -->
  <el-drawer v-model="drawer2" direction="rtl">
    <template #header>
      <h4>分配角色</h4>
    </template>
    <template #default>
      <el-form >
        <el-form-item label="用户姓名">
          <el-input v-model="userParams.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="职位列表">
          <!-- 全选 -->
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
            >
            全选
          </el-checkbox>
          <!-- checkbox组 -->
          <el-checkbox-group
            v-model="userRole"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="role in allRole"
              :key="role.id"
              :label="role"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer2 = false">取消</el-button>
        <el-button type="primary" @click="save2">确定</el-button>
      </div>
    </template>
  </el-drawer>
  </div> 
</template>

<script setup lang="ts">
import { nextTick,ref, onMounted, reactive } from 'vue'
import { reqSetUserRole, reqAllRole,reqSelectUser,reqRemoveUser,reqAddOrUpdateUser, reqUserInfo } from '@/api/acl/user'
import type {  SetRoleData, AllRole, User, UserList } from '@/api/acl/user/type'
import { ElMessage } from 'element-plus';
import { useLayoutSettingStore } from '@/store/modules/setting';
import { useUserStore } from '@/store/modules/user';

const pageNo = ref(1)
const pageSize = ref(5)
const total = ref(0)
const layoutSettingStore = useLayoutSettingStore()
const userStore = useUserStore()

// 初始化获取用户数据
const keyword = ref('')
const formRef = ref()
const userList = ref<UserList>([])
const getHasUser = async () => {
  const res = await reqUserInfo(pageNo.value, pageSize.value, keyword.value)
  if(res.code == 200) {
    total.value = res.data.total
    userList.value = res.data.records
  }
}

// 搜索
const search = () => {
  getHasUser()
  keyword.value = ''
}

// 重置
const reset = () => {
  layoutSettingStore.refresh = !layoutSettingStore.refresh
}

// 条数变化
const sizeChange = () => {
  pageNo.value = 1
  getHasUser()
}

// 抽屉
const drawer = ref(false)

// 添加修改用户
// 收集用户信息
const userParams =reactive<User>({
  username: '',
  name: '',
  password: ''
})

const addUser = () => {
  nextTick(()=>{
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
  if(userParams.id) {
    delete userParams.id
  }
  Object.assign(userParams,{
    username: '',
    name: '',
    password: ''
  })
  drawer.value = true  
}
// 收集初始名字
let oldName = ''
const updateUser = (row:User) => {
  oldName = row.username as string
  nextTick(()=>{
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
  drawer.value = true
  Object.assign(userParams, row)
}

// 表单校验规则
const checkUsername = (rule:any, value:any, callBack:any) => {
  if(value.trim().length >=5 && value.trim().length<=12) {
    callBack()
  } else {
    callBack(new Error('用户名字必须在5-12位'))
  }
}

const checkName = (rule:any, value:any, callBack:any) => {
  if(value.trim().length >=5 && value.trim().length<=12) {
    callBack()
  } else {
    callBack(new Error('用户昵称必须在5-12位'))
  }
}

const checkPassword = (rule:any, value:any, callBack:any) => {
  if(value.trim().length >=6 && value.trim().length<=15) {
    callBack()
  } else {
    callBack(new Error('用户密码必须在6-15位'))
  }
}

const rules = {
  username: [
    {required:true, trigger: 'blur', validator: checkUsername }
  ],
  name: [
    {required:true, trigger: 'blur', validator: checkName }
  ],
  password: [
    {required:true, trigger: 'blur', validator: checkPassword }
  ]
}

// 取消
const cancel = () => {
  drawer.value = false
}

// 保存按钮
const save = async () => {
  // 保证表单通过
  await formRef.value.validate()
  const res = await reqAddOrUpdateUser(userParams)
  if(res.code == 200) {
    drawer.value = false
    ElMessage({
      type: 'success',
      message: userParams.id?'更新成功~':'添加成功~'
    })
    // 浏览器自动刷新一次 每次更新完 如果更新的是自己 之前的token会过期 要刷新页面 重返登录
    // 刷新了 仓库username会变成'' 走catch线
    if(userStore.username == oldName) {
        window.location.reload()
    } else {
      getHasUser()
    }
    
  } else {
    drawer.value = false
    ElMessage({
      type: 'error',
      message: userParams.id?'更新失败~':'添加失败~'
    })
  }
}


// 删除单个用户
const deleteUser = async (userId: number) => {
  const res = await reqRemoveUser(userId)
  if(res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功~'
    })
    if(userList.value.length <= 1) {
      pageNo.value = pageNo.value - 1 <=1?1:pageNo.value - 1
    }
    getHasUser()
  }
}

// table复选框勾选触发事件
const selectIdArr = ref<User[]>([])
const selectChange = (value:any) => {
  // value 选中的row组成的数组
  selectIdArr.value = value
}

// 批量删除
const delectSelectUser = async () => {
  const idList = selectIdArr.value.map(item => item.id as number)
  const res = await reqSelectUser(idList)
  if(res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功~'
    })
    if(userList.value.length - idList.length  < 1) {
      pageNo.value = pageNo.value - 1 <=1?1:pageNo.value - 1
    }
    getHasUser()
  }
}




// 分配角色 
const drawer2 = ref(false)
const setRole = async (row:User) => {
  drawer2.value = true
  // 存储用户信息
  Object.assign(userParams, row)
  // 获取全部职位用户职位
  const res = await reqAllRole(row.id as number)
  if(res.code == 200) {
    allRole.value = res.data.allRolesList
    userRole.value = res.data.assignRoles
    const checkedCount2 = userRole.value.length
    checkAll.value = checkedCount2 === allRole.value.length
    isIndeterminate.value = checkedCount2 > 0 && checkedCount2 < allRole.value.length
  }
}


// 全选相关
const checkAll = ref(false) // 是否全选
const isIndeterminate = ref(false) // 设置全选框的状态 - √
const allRole = ref<AllRole>([])
const userRole = ref<AllRole>([])
// 全选事件
const handleCheckAllChange = (val:boolean) => {
  userRole.value = val?allRole.value:[]
  isIndeterminate.value = false
}
// 单选框change
const handleCheckedCitiesChange = (val: User[]) => {
  const checkedCount = val.length
  checkAll.value = checkedCount === allRole.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < allRole.value.length
}


// 保存职位
const save2 = async () => {
  const data: SetRoleData = {
    userId: userParams.id as number,
    roleIdList: userRole.value.map(item=>item.id as number)
  }
  const res = await reqSetUserRole(data)
  if(res.code == 200) {
    drawer2.value = false
    ElMessage({
      type: 'success',
      message: '分配职位成功~'
    })
    getHasUser()
  }
}





onMounted(()=>{
  getHasUser()
})
</script>

<style lang="scss" scoped>
  .user {
    .user-form {
      justify-content: space-between;
      display: flex;
      align-items: center;
      .el-form-item {
        margin-bottom: 0;
      }
    }
  }
</style>
